package Principal;

import static Principal.VentanaPrincipal.idUsuario;
import com.mxrck.autocompleter.TextAutoCompleter;
import de.centigrade.bizlaf.BizLafControl;
import de.centigrade.bizlaf.support.BizLafStyles;
import java.awt.Color;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import static javax.swing.JFileChooser.SAVE_DIALOG;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.plaf.FontUIResource;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import preparedstatement.DebugLevel;
import preparedstatement.StatementFactory;

/**
 *
 * @author Pascual Guerrero
 */
public final class PanelVentas extends javax.swing.JPanel {

    // String consulta;//esta es la consulta obtenida del preparedstatement
    String tipopago = "Efectivo";
    // Monedero mon;
    float cDescuento = 0.0f;//la cantgidad de descuento que se dara
    Vector especiales = new Vector();//este guarda imeis
    Vector especialesId = new Vector();//este guarda idproducto de los imeis
    String nombre2;
    public String detalleVenta = "";
    static TextAutoCompleter textAutoCompleter;
    static PreparedStatement ps;
    static ResultSet rs;
    DebugLevel debug = DebugLevel.ON;
    boolean existecliente = false;//si hay cliente
    int IdCliente = 1;// es el cliente default
    ResultSetMetaData rsm;
    DefaultTableModel dtm, dtm2;
    PrecioCantidad prcd;
    descuento desc;
    otroProducto otto;
    pasarDato dato;
    DecimalFormat nf;
    boolean unico = false;//este booleano es para ver si utilizo lector de codigo de barras
    Number number = null;
    Number number2 = null;
    FormatoTabla ft;//para el jtable coloreado
    NumberFormat fmt = NumberFormat.getInstance();//es el formato numerico
    Vector otroscompra = new Vector(); // se refiere a la venta de otros, para saber en que precio se compro 
    Thread d;//este es el trhead que imprime
imprimir imprime = new imprimir();
    public PanelVentas() {
        initComponents();

        jTable1.removeColumn(jTable1.getColumnModel().getColumn(0));
        BizLafControl.get().setStyle(jTextField1, BizLafStyles.SEARCH);
        BizLafControl.get().setStyle(jPanel3, BizLafStyles.CONTAINER);
        BizLafControl.get().setStyle(LblCliente, BizLafStyles.CONTAINER_HEADER);
        if (VentanaPrincipal.local) {
            PanelVentas.conexion.setText("Local");
            PanelVentas.conexion.setBackground(Color.red);
        } else {
            PanelVentas.conexion.setText("En Red");
            PanelVentas.conexion.setBackground(Color.green);
        }
        textAutoCompleter = new TextAutoCompleter(rfid2);
        textAutoCompleter.setMode(0);
        textAutoCompleter.setCaseSensitive(false);
        //iniciamos los modelos de las tablas
        dtm = (DefaultTableModel) this.jTable1.getModel();
        dtm2 = (DefaultTableModel) this.jTable2.getModel();
        ft = new FormatoTabla(0, dtm);
        jTable1.setDefaultRenderer(Object.class, ft);
        nf = new DecimalFormat("#,###,###,##0.00");
        recibo.setDocument(new LimitadorCaracteresFloat());
        consultarProductos();
        cargarClientes();
    }

    public static void cargarClientes() {
        textAutoCompleter.removeAll();
        try {
            ps = (PreparedStatement) local_connection.cn.prepareStatement("select nombre, paterno, materno from personas");
            rs = ps.executeQuery();
            while (rs.next()) {
                textAutoCompleter.addItem(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3));
            }
        } catch (SQLException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        }
    }

    public class LimitadorCaracteresFloat extends PlainDocument {

        @Override
        public void insertString(int arg0, String arg1, AttributeSet arg2) throws BadLocationException {
            for (int i = 0; i < arg1.length(); i++) // si no es digit, volvemos
            {
                if (!(Character.isDigit(arg1.charAt(i)) || arg1.charAt(i) == '.')) {
                    return;
                }
            }
            super.insertString(arg0, arg1, arg2);
        }
    }

    public void iniciarTabla1() {
        jTable1.getColumnModel().getColumn(1).setMaxWidth(40);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(170);
        jTable1.getColumnModel().getColumn(2).setMaxWidth(250);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(200);
        jTable1.getColumnModel().getColumn(4).setMaxWidth(50);
//        jTable1.getColumnModel().getColumn(5).setMaxWidth(50);
        //     jTable1.removeColumn(jTable1.getColumnModel().getColumn(0));

    }

    @SuppressWarnings({"empty-statement", "empty-statement"})
    void consultarProductos() {
        dtm.setRowCount(0);
        String select;
        String consultar;
        String como, where, nombre = "%";
        como = jTextField1.getText();
        while ((como.length() > 0) && (como.charAt(0) == ' ')) {
            como = como.substring(1);
        }
        StringTokenizer tokens = new StringTokenizer(como);
        while (tokens.hasMoreElements()) {
            nombre += (tokens.nextToken() + "%");
        }
        if (jComboBox2.getSelectedIndex() == 1) {
            where = "ubicacion like '%" + como + "%'";
        } else {
            where = "productos.nombre like '" + nombre + "' or descripcion like '" + nombre + "' or productos.id_producto like '%"
                    + como + "%'";
            if (!como.equals("")) {
                where += "or especiales.clave ='" + como + "'";
            }
        }
        select = "select case when stock.cantidad is null then 0 else stock.cantidad end as stock, productos.id_producto, productos.nombre, descripcion,productos.tipo, precio "
                + "from ((productos join precios on precios.id_producto = productos.id_producto and precios.cantidad=1 left outer join especiales on especiales.id_producto = productos.id_producto and especiales.vendido = 0)"
                + " LEFT OUTER JOIN stock on productos.id_producto = stock.id_producto and stock.sucursal = ? ) where( ";
        consultar = select + where;
        // System.out.println(consultar + ")and productos.activo = 1 group by productos.id_producto");
        try {
            ps = (PreparedStatement) cache_connection.cn.prepareStatement(consultar + ")and productos.activo = 1 group by productos.id_producto");
            //  System.out.println(ps.toString());
            ps.setInt(1, VentanaPrincipal.sucursal);
            rs = ps.executeQuery();
            ArrayList<Object[]> array = new ArrayList<>();

            while (rs.next()) {

                Object[] columna = new Object[dtm.getColumnCount()];
                for (int i = 0; i < columna.length; i++) {
                    columna[i] = rs.getObject(i + 1);
                }
                array.add(columna);
            }
            /*Object[][] objeto = new Object[array.size()][];
             for (int j = 0; j < array.size(); j++) {
             objeto[j] = array.get(j);
             }*/
            for (Object[] data1 : array) {
                dtm.addRow(data1);
            }
          //  dtm.setDataVector(objeto, new Object[]{"",
            //     "Codigo", "Nombre", "Descripcion", "Tipo", "Precio"});
            //iniciarTabla1();
        } catch (SQLException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        }

    }

    private void eliminarDelCarro() {
        int row = jTable2.convertRowIndexToModel(jTable2.getSelectedRow());
        if (row >= 0) {
            String tipo = (String) dtm2.getValueAt(row, 4);
            int id = (int) dtm2.getValueAt(row, 0);
            if (tipo.equals("Chip") || tipo.equals("Celular")) {
                for (int i = 0; i < especiales.size(); i++) {
                    if ((int) especialesId.elementAt(i) == id) {
                        especiales.removeElementAt(i);
                        especialesId.removeElementAt(i);
                    }
                }
            }
            if (id == -1) {
                JBdescuento.setEnabled(true);
            }
            if (id == -2) {
                int cuenta = 0;
                for (int i = 0; i <= row; i++) {
                    if (id == -2) {
                        cuenta++;
                    }
                }
                otroscompra.removeElementAt(cuenta - 1);
            }
            // System.out.println(id);
            //dtm.setRowCount(0); 
            dtm2.removeRow(row);
            actualizarCompra();
            actualizarDescuento();
        }
    }

    private void cambiardetalle()
            throws SQLException {
        int codigo, row = jTable2.convertRowIndexToModel(jTable2.getSelectedRow());
        String tipo = "";
        if (row != -1) {
            if (((int) dtm2.getValueAt(row, 0) != -1) && ((int) dtm2.getValueAt(row, 0) != -2)) {
                codigo = (int) dtm2.getValueAt(row, 0);
                tipo = (String) dtm2.getValueAt(row, 4);
                prcd = new PrecioCantidad();
                prcd.setCantidad((float) (dtm2.getValueAt(row, 1)));
                prcd.setModo(String.valueOf(dtm2.getValueAt(row, 3)));
                prcd.setPrecio((float) dtm2.getValueAt(row, 5));
                prcd.setTipo(tipo);
                if (tipo.equals("Chip") || tipo.equals("Celular")) {
                    (new editarEspeciales(null, true, tipo, codigo, especiales, especialesId, prcd)).setVisible(true);
                } else {
                    cantidas = new cantidad(null, true, codigo, prcd);
                    cantidas.setVisible(true);
                }
                if (prcd.getCantidad() != 0) {
                    dtm2.setValueAt(prcd.getCantidad(), row, 1);
                    dtm2.setValueAt(prcd.getPrecio(), row, 5);
                    dtm2.setValueAt(prcd.getModo(), row, 3);
                    dtm2.setValueAt(prcd.getCantidad() * prcd.getPrecio(), row, 6);
                    dtm2.setValueAt(prcd.getTipo(), row, 4);
                    dtm2.setValueAt((int) (prcd.getPeso() * prcd.getCantidad()), row, 7);
                    actualizarCompra();
                    actualizarDescuento();
                }
            } else if (((int) dtm2.getValueAt(row, 0) == -1)) {
                desc = new descuento();
                desc.setCantidad(cDescuento);
                desc.setTipo(String.valueOf(dtm2.getValueAt(row, 4)));
                dtm2.removeRow(row);
                detalle = new detalleDescuento(null, true, jLabel21.getText(), desc);
                detalle.setVisible(true);
                if ((desc.getTipo() != null) && (desc.getCantidad() != 0) && (desc.getUnitario() > 0)) {
                    ArrayList<Object[]> data = new ArrayList<>();
                    Object[] rows = new Object[jTable2.getColumnCount()];
                    cDescuento = desc.getCantidad();
                    rows[0] = -1;
                    rows[1] = 1.0f;
                    rows[2] = "Descuento";
                    rows[3] = desc.getTipo();
                    rows[4] = desc.getTipo();
                    rows[5] = -1 * desc.getUnitario();
                    rows[6] = -1 * desc.getUnitario();
                    rows[7] = 0;
                    data.add(rows);
                    dtm2.addRow(data.get(0));
                    actualizarCompra();
                } else {
                    JBdescuento.setEnabled(true);
                }
                desc = null;
            } else if (((int) dtm2.getValueAt(row, 0) == -2)) {
                otto = new otroProducto();
                otto.setNombre(String.valueOf(dtm2.getValueAt(row, 2)));
                otto.setCantidad((float) dtm2.getValueAt(row, 1));
                otto.setPventa(Float.parseFloat(String.valueOf(dtm2.getValueAt(row, 5))));
                otro = new venderOtro(null, true, otto);
                otro.setVisible(true);
                dtm2.removeRow(row);
                if ((otto.getNombre() != null) && (otto.getCantidad() != 0) && (otto.getPventa() != 0)) {

                    ArrayList<Object[]> data = new ArrayList<>();
                    Object[] rows = new Object[8];//8 es el numero de columnas

                    rows[0] = -2;
                    rows[1] = otto.getCantidad();
                    rows[2] = otto.getNombre();
                    rows[3] = "Unitario";
                    rows[4] = "Otro";
                    rows[5] = otto.getPventa();
                    rows[6] = otto.getCantidad() * otto.getPventa();
                    rows[7] = 0;
                    data.add(rows);
                    dtm2.addRow(data.get(0));
                    actualizarCompra();
                }
                otto = null;
            }
        }
    }

    private void actualizarDescuento() {
        if (!JBdescuento.isEnabled()) {
            float descontar, porcentaje;
            int fila = -1;
            for (int i = 0; i < dtm2.getRowCount(); i++) {
                if ((int) dtm2.getValueAt(i, 0) == -1) {
                    fila = i;
                    i = dtm2.getRowCount();
                }
            }
            if (fila != -1) {
                if (dtm2.getValueAt(fila, 3).equals("Porcentaje")) {
                    try {
                        number = fmt.parse(jLabel21.getText());
                    } catch (ParseException ex) {
                        VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
                    }

                    porcentaje = cDescuento;
                    descontar = number.floatValue() * porcentaje / 100;
                    dtm2.setValueAt(-1 * descontar, fila, 5);
                    dtm2.setValueAt(-1 * descontar, fila, 6);
                }
            }
            actualizarCompra();
        }
    }

    private void venderproducto() {//esta funcion saca el jDialog de vender productos donde viene el precio y la cantidad
        if (unico) {
            jTable1.changeSelection(0, 0, false, false);
            seleccion();
        }
        if (jTable1.getSelectedRow() != -1) {
            boolean encontrado = false;
            try {
                int row = jTable1.convertRowIndexToModel(jTable1.getSelectedRow());
                int codigo;
                String tipo = (String) dtm.getValueAt(row, 4);
                codigo = (int) dtm.getValueAt(row, 1);
                prcd = new PrecioCantidad();
                if (!unico) {
                    if (tipo.equals("Chip") || tipo.equals("Celular")) {
                        (new Especiales(null, true, prcd, codigo, tipo, "", especiales, especialesId)).setVisible(true);
                    } else {
                        cantidas = new cantidad(null, true, codigo, prcd);
                        cantidas.setVisible(true);
                    }
                } else {
                    prcd.setCantidad(1);
                    prcd.setModo("Unitario");
                    prcd.setPrecio((float) (double) dtm.getValueAt(0, 5));
                    prcd.setPeso(Integer.parseInt(peso.getText()));
                    if (tipo.equals("Chip")) {
                        (new Especiales(null, true, prcd, codigo, tipo, jTextField1.getText(), especiales, especialesId)).setVisible(true);
                    } else if (tipo.equals("Celular")) {
                        if (esEspecial(jTextField1.getText())) {
                            especiales.add(jTextField1.getText());
                            especialesId.add(codigo);
                        } else {
                            (new Especiales(null, true, prcd, codigo, tipo, "", especiales, especialesId)).setVisible(true);
                        }
                    }
                }
                for (int i = 0; i < dtm2.getRowCount(); i++) {
                    if ((int) dtm2.getValueAt(i, 0) == codigo) {
                        if (unico) {
                            dtm2.setValueAt((int) ((int) dtm2.getValueAt(i, 7) * ((float) dtm2.getValueAt(i, 1) + 1) / (float) dtm2.getValueAt(i, 1)), i, 7);
                            dtm2.setValueAt((float) dtm2.getValueAt(i, 6) * ((float) dtm2.getValueAt(i, 1) + 1) / (float) dtm2.getValueAt(i, 1), i, 6);
                            //dtm2.setValueAt((int) ((float) dtm2.getValueAt(i, 1) * (int) dtm2.getValueAt(i, 7)), i, 7);
                            dtm2.setValueAt((float) dtm2.getValueAt(i, 1) + 1, i, 1);
                        } else if (prcd.getCantidad() > 0.0) {
                            float cantidad, cantidada = cantidad = prcd.getCantidad();
                            cantidad += (float) dtm2.getValueAt(i, 1);
                            dtm2.setValueAt(cantidad, i, 1);
                            dtm2.setValueAt((int) ((int) dtm2.getValueAt(i, 7) * (cantidad) / cantidada), i, 7);
                            dtm2.setValueAt((float) dtm2.getValueAt(i, 6) * (cantidad) / cantidada, i, 6);
                        }
                        encontrado = true;
                        i = dtm2.getRowCount();
                    }
                }
                if (!encontrado) {//esto quiere decir si el producto no esta entre los productos ya en lista

                    /*    ps = (PreparedStatement) cache_connection.cn.prepareStatement("select productos.nombre, peso, precio from productos join precios on productos.id_producto = precios.id_producto where sucursal = ?  and productos.id_producto = ? order by cantidad asc limit 1");
                     ps.setInt(1, VentanaPrincipal.sucursal);
                     ps.setInt(2, codigo);
                     rs = ps.executeQuery();*/
                    ArrayList<Object[]> data = new ArrayList<>();
                    rs.next();
                    Object[] rows = new Object[jTable2.getColumnCount()];
                    if (prcd.getCantidad() > 0) {
                        rows[0] = codigo;
                        rows[1] = prcd.getCantidad();
                        rows[2] = dtm.getValueAt(row, 2);
                        rows[3] = prcd.getModo();
                        rows[4] = prcd.getTipo();
                        rows[5] = prcd.getPrecio();
                        rows[6] = prcd.getCantidad() * prcd.getPrecio();
                        rows[7] = (int) (prcd.getPeso() * prcd.getCantidad());
                        data.add(rows);
                        dtm2.addRow(data.get(0));
                    }
                }

                actualizarCompra();
                actualizarDescuento();
            } catch (SQLException ex) {
                VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
            }
        }
        unico = false;
    }

    private void aplicarDescuento() {
        if (desc == null) {
            desc = new descuento();
        }
        detalle = new detalleDescuento(null, true, jLabel21.getText(), desc);
        detalle.setVisible(true);
        if ((desc.getTipo() != null) && (desc.getCantidad() != 0)) {
            cDescuento = desc.getCantidad();
            ArrayList<Object[]> data = new ArrayList<>();
            Object[] rows = new Object[jTable2.getColumnCount()];
            rows[0] = -1;
            rows[1] = 1.0f;
            rows[2] = "Descuento";
            rows[3] = desc.getTipo();
            rows[4] = desc.getTipo();
            rows[5] = -1 * desc.getUnitario();
            rows[6] = -1 * desc.getUnitario();
            rows[7] = 0;
            data.add(rows);
            dtm2.addRow(data.get(0));
            actualizarCompra();
            JBdescuento.setEnabled(false);
        }
        desc = null;
    }

    private boolean esEspecial(String id) {
        try {
            ps = local_connection.cn.prepareStatement("select vendido from especiales where clave like ?");
            ps.setString(1, id);
            rs = ps.executeQuery();
            if (rs.next()) {
                if (rs.getInt(1) == 0) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (SQLException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        }
        return false;
    }

    private void seleccion() {
        if (jTable1.getSelectedRow() != -1) {
            jComboBox1.removeAllItems();

            int row = jTable1.convertRowIndexToModel(jTable1.getSelectedRow());
            if (row != -1) {
                try {
                    String precio;
                    int codigo;

                    codigo = (int) (dtm.getValueAt(row, 1));
                    ps = (PreparedStatement) cache_connection.cn.prepareStatement("select modelo, peso, cantidad, ubicacion from productos left outer join stock on productos.id_producto = stock.id_producto and sucursal = ? where productos.id_producto = ? ");
                    ps.setInt(2, codigo);
                    ps.setInt(1, VentanaPrincipal.sucursal);
                    rs = ps.executeQuery();
                    rs.next();
                    cd.setText(String.valueOf(codigo));
                    modelo.setText(rs.getString("modelo"));
                    peso.setText(rs.getString("peso"));
                    if (rs.getString("cantidad") != null) {
                        cantidadp.setText(rs.getString("cantidad"));
                    }
                    if (rs.getString("ubicacion") != null) {
                        ubicacionm.setText(rs.getString("ubicacion"));
                    }
                    ps = (PreparedStatement) cache_connection.cn.prepareStatement("select precio, cantidad from precios where id_producto = ? and sucursal = ?");
                    ps.setInt(1, codigo);
                    ps.setInt(2, VentanaPrincipal.sucursal);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        precio = "(+" + rs.getString("cantidad") + ") " + rs.getString("precio");
                        jComboBox1.addItem(precio);
                    }
                } catch (SQLException ex) {
                    VentanaPrincipal.logger.log(Level.SEVERE, null, ex);

                }
            }
        }
    }

    private void actualizarCompra() {
        int cproductos = 0, pesos = 0;
        float total = 0.0f, totalneto = 0.0f;
        lineas.setText(String.valueOf(dtm2.getRowCount()));
        for (int i = 0; i < dtm2.getRowCount(); i++) {
            cproductos += (float) dtm2.getValueAt(i, 1);
            pesos += (int) dtm2.getValueAt(i, 7);
            total += (float) dtm2.getValueAt(i, 6);
            if ((int) dtm2.getValueAt(i, 0) != -1) {
                totalneto += (float) dtm2.getValueAt(i, 6);
            }
        }
        pesoTotal.setText(String.valueOf(pesos));
        cantidadProductos.setText(String.valueOf(cproductos));
        jLabel20.setText(String.valueOf(nf.format(total)));
        jLabel21.setText(String.valueOf(nf.format(totalneto)));
    }

    void imprimirTicket(int t, int c, String tipoPago) {
        Date date = new Date();
        SimpleDateFormat fecha = new SimpleDateFormat("dd/MM/yyyy");
        SimpleDateFormat hora = new SimpleDateFormat("hh:mm:ss aa");
        if (existecliente) {
            Ticket.nombre = LblCliente.getText();
        }
        if (recibo.getText().equals("")) {
            recibo.setText("0");
        }
        Ticket.tipopago = tipoPago;
        Ticket.AddSubCabecera("" + fecha.format(date) + " " + hora.format(date));
        Ticket.AddSubCabecera("Ticket # " + String.valueOf(t));
        Ticket.AddSubCabecera("Folio: " + String.valueOf(c));
        for (int i = 0; i < jTable2.getRowCount(); i++) {
            Ticket.AddNombre(String.valueOf(dtm2.getValueAt(i, 2)));
            Ticket.AddImporte(String.valueOf(dtm2.getValueAt(i, 6)));
            Ticket.AddItem(String.valueOf(dtm2.getValueAt(i, 1)), String.valueOf(dtm2.getValueAt(i, 0)), String.valueOf(dtm2.getValueAt(i, 5)));
        }

        Ticket.setTotal(jLabel20.getText());
        Ticket.setPeso(pesoTotal.getText());
        // if(!recibo.getText().equals(""))
        Ticket.setRecibido(recibo.getText());
       // 
        if (credito.isSelected()) {
            imprimir.twice = true;
            Ticket.credito = true;
            System.out.println("doble");
        } else {
            imprimir.twice = false;
        }
        d = new Thread(imprime);
        d.start();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        JBeliminar = new javax.swing.JButton();
        JBdescuento = new javax.swing.JButton();
        JBgastos = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel13 = new javax.swing.JLabel();
        JBverDetallesVenta = new javax.swing.JButton();
        jLabel15 = new javax.swing.JLabel();
        jLabel21 = new javax.swing.JLabel();
        cantidadProductos = new javax.swing.JLabel();
        lineas = new javax.swing.JLabel();
        pesoTotal = new javax.swing.JLabel();
        JBfinalizarVenta = new javax.swing.JButton();
        JBcancelarVenta = new javax.swing.JButton();
        jLabel14 = new javax.swing.JLabel();
        recibo = new javax.swing.JTextField();
        jLabel20 = new javax.swing.JLabel();
        jLabel19 = new javax.swing.JLabel();
        jLabel22 = new javax.swing.JLabel();
        credito = new javax.swing.JCheckBox();
        JBverdetalle = new javax.swing.JButton();
        JBvender = new javax.swing.JButton();
        JBbazar = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        JBeditar = new javax.swing.JButton();
        JBvenderOtro = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        modelo = new javax.swing.JLabel();
        cd = new javax.swing.JLabel();
        ubicacionm = new javax.swing.JLabel();
        cantidadp = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jComboBox2 = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        peso = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        rfid2 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        LblCliente = new javax.swing.JLabel();
        tipoPago = new javax.swing.JComboBox();
        jLabel11 = new javax.swing.JLabel();
        conexion = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        jPanel3.setMinimumSize(new java.awt.Dimension(400, 279));
        jPanel3.setPreferredSize(new java.awt.Dimension(800, 579));

        JBeliminar.setText("Eliminar");
        JBeliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBeliminarActionPerformed(evt);
            }
        });

        JBdescuento.setText("Descuento");
        JBdescuento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBdescuentoActionPerformed(evt);
            }
        });

        JBgastos.setText("Gastos");
        JBgastos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBgastosActionPerformed(evt);
            }
        });

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Existencia", "Codigo", "Nombre", "Descripcion", "Tipo", "Precio"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                jTable1MouseEntered(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jTable1MouseReleased(evt);
            }
        });
        jTable1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jTable1PropertyChange(evt);
            }
        });
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTable1KeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTable1KeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(1).setMaxWidth(45);
            jTable1.getColumnModel().getColumn(4).setMaxWidth(120);
            jTable1.getColumnModel().getColumn(5).setMaxWidth(68);
        }

        jLabel13.setText("En lista:");

        JBverDetallesVenta.setText("Ver Detalles");
        JBverDetallesVenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBverDetallesVentaActionPerformed(evt);
            }
        });

        jLabel15.setText("Peso total:");

        jLabel21.setText("---");

        cantidadProductos.setText("---");

        lineas.setText("---");

        pesoTotal.setText("---");

        JBfinalizarVenta.setText("Finalizar Venta");
        JBfinalizarVenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBfinalizarVentaActionPerformed(evt);
            }
        });

        JBcancelarVenta.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        JBcancelarVenta.setText("Cancelar Venta");
        JBcancelarVenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBcancelarVentaActionPerformed(evt);
            }
        });

        jLabel14.setText("Productos:");

        recibo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                reciboActionPerformed(evt);
            }
        });
        recibo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                reciboKeyReleased(evt);
            }
        });

        jLabel20.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel20.setText("---");

        jLabel19.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel19.setText("$");

        jLabel22.setText("$");

        credito.setText("Credito");
        credito.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                creditoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel19)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel20))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel13)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(10, 10, 10)
                                        .addComponent(lineas)))
                                .addGap(37, 37, 37)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel14)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(10, 10, 10)
                                        .addComponent(cantidadProductos)))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel15)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(10, 10, 10)
                                        .addComponent(pesoTotal))))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(JBverDetallesVenta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(JBcancelarVenta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(JBfinalizarVenta))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel22)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel21))
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(credito)
                                .addComponent(recibo, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(jLabel14)
                    .addComponent(jLabel15))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lineas)
                    .addComponent(cantidadProductos)
                    .addComponent(pesoTotal))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel20)
                        .addComponent(credito))
                    .addComponent(jLabel19))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel21, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel22))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(recibo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(JBverDetallesVenta, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(JBcancelarVenta))
                    .addComponent(JBfinalizarVenta, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        JBverdetalle.setText("Ver Detalle");
        JBverdetalle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBverdetalleActionPerformed(evt);
            }
        });

        JBvender.setText("Vender");
        JBvender.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBvenderActionPerformed(evt);
            }
        });

        JBbazar.setText("Saldos");
        JBbazar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBbazarActionPerformed(evt);
            }
        });

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Cantidad", "Nombre", "Modo", "Tipo", "P Unit", "Importe", "Peso"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Float.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Float.class, java.lang.Float.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable2MouseClicked(evt);
            }
        });
        jTable2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTable2KeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(jTable2);

        JBeditar.setText("Editar");
        JBeditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBeditarActionPerformed(evt);
            }
        });

        JBvenderOtro.setText("Vender Otro");
        JBvenderOtro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBvenderOtroActionPerformed(evt);
            }
        });

        modelo.setText("------");

        cd.setText("------");

        ubicacionm.setText("------");

        cantidadp.setText("------");

        jLabel3.setText("Codigo:");

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Por NOMBRE y DESCRIPCION", "Por CODIGO UBICACION" }));
        jComboBox2.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                jComboBox2PopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            }
        });
        jComboBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox2ActionPerformed(evt);
            }
        });

        jLabel10.setText("Peso:");

        jLabel5.setText("Modelo:");

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jLabel7.setText("Cantidad:");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel2.setText("$");

        peso.setText("------");
        peso.setToolTipText("");

        jLabel8.setText("Ubicacion:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cantidadp, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(peso, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(cd, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(modelo, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(51, 51, 51))
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                            .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(ubicacionm)
                            .addGap(125, 125, 125))))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(9, 9, 9)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addComponent(jLabel3))
                    .addComponent(cd))
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addComponent(jLabel5))
                    .addComponent(modelo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(cantidadp)
                    .addComponent(jLabel10)
                    .addComponent(peso))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(ubicacionm, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(13, 13, 13))
        );

        jLabel1.setText("Acciones:");

        rfid2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rfid2ActionPerformed(evt);
            }
        });
        rfid2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                rfid2KeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                rfid2KeyReleased(evt);
            }
        });

        jLabel4.setText("Cliente:");

        tipoPago.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Efectivo", "Tarjeta Credito", "Transferencia", "Cheque", "Deposito", "Cotización", "PayPal" }));

        jLabel11.setText("Tipo de Pago:");

        conexion.setEditable(false);
        conexion.setBackground(new java.awt.Color(51, 255, 51));
        conexion.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        conexion.setForeground(new java.awt.Color(255, 255, 255));
        conexion.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        conexion.setText("En Red");
        conexion.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                conexionMouseClicked(evt);
            }
        });
        conexion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                conexionActionPerformed(evt);
            }
        });

        jButton1.setText("Ver Stock");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(JBverdetalle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(JBvender, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(JBvenderOtro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addComponent(JBdescuento, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(JBeditar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(JBeliminar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(JBbazar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(JBgastos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(conexion)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 451, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 451, Short.MAX_VALUE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(LblCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(jPanel3Layout.createSequentialGroup()
                            .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(tipoPago, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addComponent(rfid2, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {JBbazar, JBgastos, JBvenderOtro});

        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addGap(11, 11, 11)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGap(14, 14, 14)
                                .addComponent(conexion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(JBvender)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(JBverdetalle)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(JBvenderOtro)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(JBbazar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(JBgastos)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 77, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                                .addGap(13, 13, 13)))
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel3Layout.createSequentialGroup()
                                        .addComponent(JBdescuento)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(JBeditar)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(JBeliminar))
                                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(0, 30, Short.MAX_VALUE))))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGap(43, 43, 43)
                                .addComponent(rfid2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGap(7, 7, 7)
                                .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(tipoPago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(LblCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 811, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 562, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void JBeliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBeliminarActionPerformed
        eliminarDelCarro();
    }//GEN-LAST:event_JBeliminarActionPerformed

    private void JBdescuentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBdescuentoActionPerformed
        if (jTable2.getRowCount() != -1) {
            aplicarDescuento();
        }


    }//GEN-LAST:event_JBdescuentoActionPerformed

    private void JBgastosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBgastosActionPerformed
        gastos gastar = new gastos(null, true, idUsuario);
        gastar.setVisible(true);
        // TODO add your handling code here:
    }//GEN-LAST:event_JBgastosActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        seleccion();
        if (evt.getClickCount() == 2) {
            venderproducto();
        }


    }//GEN-LAST:event_jTable1MouseClicked

    private void jTable1MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseEntered
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1MouseEntered

    private void jTable1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseReleased
        seleccion();
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1MouseReleased

    private void jTable1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jTable1PropertyChange
        //    seleccion();
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1PropertyChange

    private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyPressed
    }//GEN-LAST:event_jTable1KeyPressed

    private void jTable1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyReleased
        seleccion();
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1KeyReleased

    private void JBfinalizarVentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBfinalizarVentaActionPerformed
        if (!VentanaPrincipal.sincronizando) {
            if (dtm2.getRowCount() > 0) {
                int ban = 0;//credito asignado
                boolean valido = true;//indica si la compra puede continuar
                float cambio;
                local_connection.checkConnection();
                if (recibo.getText().equals("")) {
                    recibo.setText("0");
                }
                tipopago = (String) tipoPago.getSelectedItem();
                if (!credito.isSelected() && !tipopago.equals("Cotización")) {
                    if (!recibo.getText().equals("")) {
                        try {
                            number = fmt.parse(jLabel20.getText());
                        } catch (ParseException ex) {
                            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
                        }
                        cambio = Float.parseFloat(recibo.getText()) - number.floatValue();
                    } else {
                        cambio = -1;
                    }
                } else {
                    cambio = 0;
                }
                if (credito.isSelected()) {
                    if (existecliente == false) {
                        valido = false;
                    }
                }
                if ((cambio >= 0) && valido == true) {
                    try {
                        int nticket, folio;
                        {
                            ps = StatementFactory.getStatement(local_connection.cn, "insert into venta(id_usuario,id_cliente,tipopago,sucursal,caja,activo,fecha,detalle) values(?,?,?,?,?,?,CURRENT_TIMESTAMP,?)", debug);
                            ps.setInt(1, idUsuario);
                            ps.setInt(2, IdCliente);
                            ps.setString(3, tipopago);
                            ps.setInt(4, VentanaPrincipal.sucursal);
                            ps.setInt(5, VentanaPrincipal.caja);
                            ps.setInt(6, (tipopago.equals("Cotización")) ? 0 : 1);
                            ps.setString(7, detalleVenta);
                            VentanaPrincipal.guardarCache(ps, "venta", true);
                            if (!VentanaPrincipal.local) {
                                ps = (PreparedStatement) local_connection.cn.prepareStatement(ps.toString());
                            }
                            ps.execute();
                            ps = (PreparedStatement) local_connection.cn.prepareStatement("select folio,ticket from venta where caja = ? and sucursal = ? order by folio desc limit 1");
                            ps.setInt(1, VentanaPrincipal.caja);
                            ps.setInt(2, VentanaPrincipal.sucursal);
                            rs = ps.executeQuery();
                            rs.next();
                            folio = rs.getInt(1);
                            nticket = rs.getInt(2);
                        }
                        for (int i = 0; i < especiales.size(); i++) {
                            ps = StatementFactory.getStatement(local_connection.cn, "update especiales set vendido = (select folio from venta where caja = ? and sucursal = ? order by folio desc limit 1) where clave like ?", debug);
                            ps.setInt(1, VentanaPrincipal.caja);
                            ps.setInt(2, VentanaPrincipal.sucursal);
                            ps.setString(3, String.valueOf(especiales.get(i)));
                            ps.execute();
                            VentanaPrincipal.guardarCache(ps, "detalleventa", true);
                        }
                        for (int i = 0; i < jTable2.getRowCount(); i++) {
                            {
                                ps = StatementFactory.getStatement(local_connection.cn, "insert into detalleventa(cantidad,modo,preciovendido,id_producto,folio) values(?,?,?,?,(select folio from venta where caja = ? and sucursal = ? order by folio desc limit 1))", debug);
                                ps.setFloat(1, (float) dtm2.getValueAt(i, 1));
                                ps.setString(2, String.valueOf(dtm2.getValueAt(i, 3)));
                                ps.setFloat(3, (float) dtm2.getValueAt(i, 5));
                                ps.setString(4, String.valueOf(dtm2.getValueAt(i, 0)));
                                ps.setInt(5, VentanaPrincipal.caja);
                                ps.setInt(6, VentanaPrincipal.sucursal);
                                ps.execute();
                                VentanaPrincipal.guardarCache(ps, "detalleventa", true);
                            }

                            if (Integer.valueOf(String.valueOf(dtm2.getValueAt(i, 0))) == -2) {
                                {
                                    String last = (VentanaPrincipal.local) ? "last_insert_rowid" : "LAST_INSERT_ID";
                                    ps = StatementFactory.getStatement(local_connection.cn, "Insert into otros (nombre,detalle_venta) values(?," + last + "())", debug);
                                    ps.setString(1, (String) dtm2.getValueAt(i, 2));
                                    ps.execute();
                                    VentanaPrincipal.guardarCache(ps, "otros", true);
                                    ps = StatementFactory.getStatement(local_connection.cn, "update detalleventa set preciocompra = ? where idetalle = (select detalle_venta from otros where idotros = " + last + "())", debug);
                                    ps.setFloat(1, (float) otroscompra.elementAt(0));
                                    ps.execute();
                                    VentanaPrincipal.guardarCache(ps, "detalleventa", true);
                                }
                                otroscompra.removeElementAt(0);
                            }
                        }
                        if (!credito.isSelected() && !tipopago.equals("Cotización")) {
                            if (VentanaPrincipal.imprimir) {
                                imprimirTicket(nticket, folio, tipopago);
                            }
                            UIManager.put(
                                    "OptionPane.messageFont",
                                    new FontUIResource(new Font("Verdana", Font.BOLD, 32)));
                            JOptionPane.showMessageDialog(null, "Su cambio:\n$" + nf.format(cambio));
                            UIManager.put(
                                    "OptionPane.messageFont",
                                    new FontUIResource(new Font("Verdana", Font.BOLD, 12)));
                            recibo.setText("");
                            int estado;
                            ps = (PreparedStatement) cache_connection.cn.prepareStatement("select estado from numeros");
                            rs = ps.executeQuery();
                            if (rs.next()) {
                                estado = rs.getInt(1);
                            } else {
                                estado = 0;
                            }
                            if (estado == 1) {
                                ps = (PreparedStatement) local_connection.cn.prepareStatement("call monedero(?)");
                                ps.setInt(1, folio);
                                ps.execute();
                            }
                        }
                        /*if (tipopago.equals("Cotización")) {
                         guardarcot(folio);
                         guardarcotimg(folio);
                         }*/
                        if (credito.isSelected() && existecliente == true) {
                            float total = 0;
                            try {
                                number = fmt.parse(jLabel20.getText());
                                cambio = number.floatValue();
                            } catch (ParseException ex) {
                                VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
                            }
                            if (!recibo.getText().equals("")) {
                                total = Float.parseFloat(recibo.getText());
                                cambio -= total;
                            }
                            if (number.floatValue() > total) {
                                ps = StatementFactory.getStatement(local_connection.cn, "INSERT INTO credito(folio,credito) values(?,?)", debug);
                                ps.setInt(1, folio);
                                ps.setFloat(2, cambio);
                                ps.execute();
                                JOptionPane.showMessageDialog(null, "Se agrego: $" + cambio + " al cliente:\n" + nombre2);
                                existecliente = false;
                                VentanaPrincipal.guardarCache(ps, "credito", true);
                                if (VentanaPrincipal.imprimir) {
                                    Ticket.credito = true;
                                    Ticket.saldo = cambio;
                                    Ticket.nombre = LblCliente.getText();
                                  //  System.out.println(cambio);
                                    imprimirTicket(nticket, folio, tipopago);
                                }
                            } else {
                                ban = 1;
                            }
                        }
                        // JBcancelarVenta.doClick();
                    } catch (SQLException | HeadlessException | NumberFormatException e) {
                        VentanaPrincipal.logger.log(Level.INFO, null, e);
                    }
                }
                if (!valido) {
                    JOptionPane.showMessageDialog(null, "Ingresa un Cliente");
                } else if (valido && (cambio < 0)) {
                    JOptionPane.showMessageDialog(null, "Cantidad insuficiente o incorrecta");
                } else {
                    this.JBcancelarVenta.doClick();
                }

            }
        }
    }//GEN-LAST:event_JBfinalizarVentaActionPerformed

    void guardarcot(int folio) {
        File file;
        file = null;
        final JFileChooser fileopen;
        fileopen = new JFileChooser() {
            @Override
            public void approveSelection() {
                File f = getSelectedFile();
                if (f.exists() && getDialogType() == SAVE_DIALOG) {
                    int result = JOptionPane.showConfirmDialog(this,
                            "Este archivo ya existe, ¿Quieres sobreescribirlo?", "Archivo Existente",
                            JOptionPane.YES_NO_CANCEL_OPTION);
                    switch (result) {
                        case JOptionPane.YES_OPTION:
                            super.approveSelection();
                            return;
                        case JOptionPane.CANCEL_OPTION:
                            cancelSelection();
                            return;
                        default:
                            return;
                    }
                }
                super.approveSelection();
            }
        };
        int ret = fileopen.showSaveDialog(null);
        if (ret == JFileChooser.APPROVE_OPTION) {
            file = new File(fileopen.getSelectedFile() + ".pdf");
        }
        try {
            String proveedor = JOptionPane.showInputDialog(this, "Ingresa el numero de Provedor");
            URL resource = facturacion.class.getResource("/Cotizacion/Cotizacion.jasper");
            JasperReport reporte;
            reporte = (JasperReport) JRLoader.loadObject(resource);
            Map<String, Object> parametros = new HashMap<>();
            parametros.put("Folio", String.valueOf(folio));
            parametros.put("Proveedor", proveedor);
            JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, local_connection.cn);
            JRExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            new FileWriter(file);
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE, file);
            exporter.exportReport();
            //System.gc();
            // TODO add your handling code here:
        } catch (JRException | IOException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        }
    }

    void guardarcotimg(int folio) {
        File file = null;
        final JFileChooser fileopen = new JFileChooser() {
            @Override
            public void approveSelection() {
                File f = getSelectedFile();
                if (f.exists() && getDialogType() == SAVE_DIALOG) {
                    int result = JOptionPane.showConfirmDialog(this,
                            "Este archivo ya existe, ¿Quieres sobreescribirlo?", "Archivo Existente",
                            JOptionPane.YES_NO_CANCEL_OPTION);
                    switch (result) {
                        case JOptionPane.YES_OPTION:
                            super.approveSelection();
                            return;
                        case JOptionPane.CANCEL_OPTION:
                            cancelSelection();
                            return;
                        default:
                            return;
                    }
                }
                super.approveSelection();
            }
        };
        int ret = fileopen.showSaveDialog(null);
        if (ret == JFileChooser.APPROVE_OPTION) {
            file = new File(fileopen.getSelectedFile() + ".pdf");
        }
        try {
            URL resource = facturacion.class.getResource("/Cotizacion/imagenproducto.jasper");
            JasperReport reporte;
            reporte = (JasperReport) JRLoader.loadObject(resource);
            Map<String, Object> parametros = new HashMap<>();
            parametros.put("Folio", String.valueOf(folio));
            JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, local_connection.cn);
            JRExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            new FileWriter(file);
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE, file);
            exporter.exportReport();
            //System.gc();
            // TODO add your handling code here:
        } catch (JRException | IOException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        }
    }

    private void JBcancelarVentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBcancelarVentaActionPerformed
        dtm2.setRowCount(0);
        credito.setSelected(false);
        actualizarCompra();
        if(!VentanaPrincipal.imprimir){
        Ticket.credito = false;
        imprimir.twice = false;}
        JBdescuento.setEnabled(true);
        cDescuento = 0.0f;
        otroscompra.clear();
        IdCliente = 1;
        existecliente = false;
        LblCliente.setText("");
        recibo.setText("");
        detalleVenta = "";
        tipoPago.setSelectedIndex(0);
        especialesId.clear();
        especiales.clear();
        try {
            Thread.currentThread().sleep(3000);
        } catch (InterruptedException ex) {
            VentanaPrincipal.logger.log(Level.INFO, null, ex);
        }
       // jTextField1.requestFocus();


    }//GEN-LAST:event_JBcancelarVentaActionPerformed

    private void reciboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_reciboActionPerformed
    }//GEN-LAST:event_reciboActionPerformed

    private void reciboKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_reciboKeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            JBfinalizarVenta.doClick();
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_reciboKeyReleased

    private void JBverdetalleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBverdetalleActionPerformed
        int row;
        row = jTable1.convertRowIndexToModel(jTable1.getSelectedRow());
        if (row != -1) {
            detalleproducto detail = new detalleproducto(null, true, (int) (dtm.getValueAt(row, 1)));
            detail.setVisible(true);
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_JBverdetalleActionPerformed

    private void JBvenderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBvenderActionPerformed

        if (jTable1.getSelectedRowCount() != 0) {
            venderproducto();
        }
    }//GEN-LAST:event_JBvenderActionPerformed

    private void JBbazarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBbazarActionPerformed
        bazar ventabazar = new bazar(null, true, idUsuario, "bazar", "");
        ventabazar.setVisible(true);
        // TODO add your handling code here:
    }//GEN-LAST:event_JBbazarActionPerformed

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyReleased
        consultarProductos();
    }//GEN-LAST:event_jTextField1KeyReleased

    private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked
        if (evt.getClickCount() == 2) {
            try {
                cambiardetalle();
            } catch (SQLException ex) {
                VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
            }
        }

        // TODO add your handling code here:
    }//GEN-LAST:event_jTable2MouseClicked

    private void jTable2KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable2KeyReleased
        int row = jTable2.convertRowIndexToModel(jTable2.getSelectedRow());
        if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
            eliminarDelCarro();
            JBdescuento.setEnabled(true);
        }
        if (row >= 0) {
            if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                recibo.requestFocus();
            }
            if (evt.getKeyCode() == KeyEvent.VK_ADD) {
                String tipo = (String) dtm2.getValueAt(row, 4);
                int codigo = (int) dtm2.getValueAt(row, 0);
                if (tipo.equals("Chip") || tipo.equals("Celular")) {
                    (new Especiales(null, true, prcd, codigo, tipo, "", especiales, especialesId)).setVisible(true);
                    if (prcd.cantidad > 0.0f) {
                        agregarAlCarro(row);
                    }
                } else {
                    agregarAlCarro(row);
                }
            }
            if ((evt.getKeyCode() == KeyEvent.VK_SUBTRACT) && ((float) dtm2.getValueAt(row, 1) > 1)) {
                String tipo = (String) dtm2.getValueAt(row, 4);
                int codigo = (int) dtm2.getValueAt(row, 0);
                if (tipo.equals("Chip") || tipo.equals("Celular")) {
                    int tam = especiales.size();
                    /*System.out.println("antes de iniciar"+especiales.size());
                     for (int i = 0; i < especiales.size(); i++) {
                     System.out.println(especiales.get(i)+ "-" + especialesId.get(i));
                     }*/
                    (new restarEspecialDelCarro(null, true, codigo, especiales, especialesId, tipo)).setVisible(true);
                    /*System.out.println("despues de iniciar");
                     for (int i = 0; i < especiales.size(); i++) {
                     System.out.println(especiales.get(i) + "-" + especialesId.get(i));
                     }*/
                    if (tam != especiales.size()) {
                        substraerDelCarro(row);
                    }
                } else {
                    substraerDelCarro(row);
                }
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable2KeyReleased
    private void agregarAlCarro(int row) {
        float cantidadd = (float) dtm2.getValueAt(row, 1) + 1;
        int pesos = (int) ((int) dtm2.getValueAt(row, 7) / (cantidadd - 1));
        float preciou = (float) dtm2.getValueAt(row, 5);
        dtm2.setValueAt(cantidadd, row, 1);
        dtm2.setValueAt((float) cantidadd * preciou, row, 6);
        dtm2.setValueAt((int) (cantidadd * pesos), row, 7);
        actualizarCompra();
        actualizarDescuento();
    }

    private void substraerDelCarro(int row) {
        float cantidadd = (float) dtm2.getValueAt(row, 1) - 1;
        int pesos = (int) ((int) dtm2.getValueAt(row, 7) / (cantidadd + 1));
        float preciou = (float) dtm2.getValueAt(row, 5);
        dtm2.setValueAt(cantidadd, row, 1);
        dtm2.setValueAt((float) cantidadd * preciou, row, 6);
        dtm2.setValueAt((int) (cantidadd * pesos), row, 7);
        actualizarCompra();
        actualizarDescuento();
    }
    private void JBeditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBeditarActionPerformed
        try {
            cambiardetalle();
        } catch (SQLException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_JBeditarActionPerformed

    private void JBvenderOtroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBvenderOtroActionPerformed
        otto = new otroProducto();
        otro = new venderOtro(null, true, otto);
        otro.setVisible(true);
        if ((otto.getNombre() != null) && (otto.getCantidad() != 0) && (otto.getPventa() != 0)) {
            ArrayList<Object[]> data = new ArrayList<>();
            Object[] rows = new Object[dtm2.getColumnCount()];
            otroscompra.add(otto.getPcompra());
            rows[0] = -2;
            rows[1] = otto.getCantidad();
            rows[2] = otto.getNombre();
            rows[3] = "Unitario";
            rows[4] = "Otro";
            rows[5] = otto.getPventa();
            rows[6] = otto.getCantidad() * otto.getPventa();
            rows[7] = 0;
            data.add(rows);
            dtm2.addRow(data.get(0));
            actualizarCompra();
        }
        otto = null;
    }//GEN-LAST:event_JBvenderOtroActionPerformed

    private void jComboBox2PopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jComboBox2PopupMenuWillBecomeInvisible
        consultarProductos();
    }//GEN-LAST:event_jComboBox2PopupMenuWillBecomeInvisible

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void rfid2KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_rfid2KeyPressed
    }//GEN-LAST:event_rfid2KeyPressed

    private void rfid2KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_rfid2KeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            try {
                String id = rfid2.getText();
                String nombre = (VentanaPrincipal.local) ? "nombre||' '||paterno||' '||materno" : "concat(nombre,' ',paterno,' ',materno)";
                ps = (PreparedStatement) local_connection.cn.prepareStatement("Select id_persona, " + nombre + " from personas where " + nombre + " like '" + id + "'  or rfid = '" + id + "'"); //System.out.println("Select email, rfc, calle, numero_interior, numero_exterior, colonia, ciudad, cp, estado,id_persona from personas where concat(nombre,' ',paterno,' ',materno) like '" + cliente.getText() + "'");
                rs = ps.executeQuery();
                if (rs.next()) {
                    nombre2 = rs.getString(2);
                    LblCliente.setText(rs.getString(2));
                    existecliente = true;
                    IdCliente = rs.getInt(1);
                    rfid2.setText("");
                }

            } catch (SQLException ex) {
                VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_rfid2KeyReleased

    private void rfid2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rfid2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_rfid2ActionPerformed

    private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox2ActionPerformed

    private void conexionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_conexionActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_conexionActionPerformed

    private void conexionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_conexionMouseClicked
        if (VentanaPrincipal.local) {
            local_connection.checkConnection();
        } else {
            local_connection.trabajarLocal(true);
            try {
                local_connection.cn = cache_connection.getconnect();
            } catch (SQLException ex) {
                VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_conexionMouseClicked

    private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed

        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            if (jTable1.getRowCount() == 1) {
                unico = true;
                venderproducto();
            }
            if ((jTable1.getRowCount() == 0) && (!jTextField1.getText().equals(""))) {
                try {
                    ps = StatementFactory.getStatement(local_connection.cn, "INSERT INTO pedidos(nombre,sucursal) VALUES(?,?)", debug);
                    ps.setString(1, jTextField1.getText());
                    ps.setInt(2, VentanaPrincipal.sucursal);
                    ps.execute();
                    VentanaPrincipal.guardarCache(ps, "pedidos", true);
                } catch (SQLException ex) {
                    VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
                }
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1KeyPressed

    private void JBverDetallesVentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBverDetallesVentaActionPerformed
        (new DetalleVenta(this)).setVisible(true);
        // TODO add your handling code here:
    }//GEN-LAST:event_JBverDetallesVentaActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (!VentanaPrincipal.sincronizando) {
            int row = jTable1.getSelectedRow();
            if (row != -1) {
                row = jTable1.convertRowIndexToModel(row);
                stock ver = new stock(null, true, (int) (dtm.getValueAt(row, 1)));
                ver.setVisible(true);
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void creditoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_creditoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_creditoActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton JBbazar;
    private javax.swing.JButton JBcancelarVenta;
    private javax.swing.JButton JBdescuento;
    private javax.swing.JButton JBeditar;
    private javax.swing.JButton JBeliminar;
    private javax.swing.JButton JBfinalizarVenta;
    private javax.swing.JButton JBgastos;
    private javax.swing.JButton JBvender;
    private javax.swing.JButton JBvenderOtro;
    private javax.swing.JButton JBverDetallesVenta;
    private javax.swing.JButton JBverdetalle;
    private javax.swing.JLabel LblCliente;
    private javax.swing.JLabel cantidadProductos;
    private javax.swing.JLabel cantidadp;
    private javax.swing.JLabel cd;
    public static javax.swing.JTextField conexion;
    private javax.swing.JCheckBox credito;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JLabel lineas;
    private javax.swing.JLabel modelo;
    private javax.swing.JLabel peso;
    private javax.swing.JLabel pesoTotal;
    private javax.swing.JTextField recibo;
    private javax.swing.JTextField rfid2;
    private javax.swing.JComboBox tipoPago;
    private javax.swing.JLabel ubicacionm;
    // End of variables declaration//GEN-END:variables
    private JDialog cantidas;
    public detalleDescuento detalle;
    public venderOtro otro;
}
